package com.zhl.gradledemo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.util.CollectionUtils;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Collection;

/**
 * 数据库工具
 *
 * @author austinChen
 * Created by austinChen on 2019/7/26 14:16.
 */
@Slf4j
public final class DbUtil {

    private String url;
    private String user;
    private String password;

    private final static int MAX_ROW_NUM=20;

    /**
     * @param collection 一次删除的集合
     */
    public static void checkDeleteNum(Collection collection)
    {
        if(CollectionUtils.isEmpty(collection))
        {
            log.error("禁止删除空集合数据");
        }
        else if(collection.size()>MAX_ROW_NUM)
        {
            log.error("禁止一次删除超过20条数据");
        }
    }


    /**
     * @param rowNum 一次删除的行数，禁止一次超过20条
     */
    public static void checkDeleteNum(int rowNum)
    {
        if(rowNum>MAX_ROW_NUM)
        {
            log.error("禁止一次删除超过20条数据");
        }
    }


    public DbUtil(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.password = password;
    }


    public boolean runSql(String sqlPath) {
        try (Connection conn = DriverManager.getConnection(url, user, password); FileReader fr = new FileReader(sqlPath)) {
            // 创建ScriptRunner，用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            // 执行SQL脚本
            runner.runScript(fr);
            // 关闭连接
            conn.close();
            // 若成功，打印提示信息
            log.info("脚本{}执行成功",sqlPath);
        } catch (Exception e) {
            log.error("执行脚本出错", e);
            return false;
        }
        return true;
    }

}
